package com.fullertontech.framework.fileupload.oss;

import java.io.File;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.fullertontech.framework.fileupload.FileObject;
import com.fullertontech.framework.fileupload.FileUploadClient;
import com.fullertontech.framework.fileupload.FileUploadClientGroup;

class OssClientGroup implements FileUploadClientGroup{
  private Map<String,OssClient> clientMap=new HashMap<>();

  public OssClientGroup(String endpoint,String[] bucketNameArray, String accessKeyId, String secretAccessKey) {
    Stream.of(bucketNameArray).forEach(bucketName->{
      clientMap.put(bucketName, new OssClient(endpoint,bucketName,accessKeyId,secretAccessKey));
    });
  }

  static class OssClient implements FileUploadClient{
    private final String style = "image/resize,m_lfit,w_%s,h_%s";
    private OSSClient ossClient;
    private String bucketName;
    private OssClient(String endpoint,DefaultCredentialProvider credsProvider) {
      ossClient=new OSSClient(endpoint, credsProvider,null);
    }
    public OssClient(String endpoint,String bucketName, String accessKeyId, String secretAccessKey) {
      this(endpoint, new DefaultCredentialProvider(accessKeyId,secretAccessKey));
      this.bucketName=bucketName;
    }
    @Override
    public FileObject upload(File file, String ext, String fileName) throws Exception {
      String key=fileName.concat(".").concat(ext);
      ossClient.putObject(bucketName, key, file);
      return new OssFileObject() {
        
        @Override
        public String key() {
          return key;
        }
      };
    }
    @Override
    public void delete(FileObject fileObject) throws Exception {
      ossClient.deleteObject(bucketName, fileObject.fileId()[0]);
    }

    @Override
    public String getFileUrl(FileObject fileObject) throws Exception {
      Calendar expireDate = Calendar.getInstance();
      expireDate.add(Calendar.MINUTE, 10);
      return ossClient.generatePresignedUrl(bucketName, fileObject.fileId()[0],expireDate.getTime()).toURI().toURL().toString();
    }
    @Override
    public String getFileUrl(FileObject fileObject,int width,int height) throws Exception {
      GeneratePresignedUrlRequest req = new  GeneratePresignedUrlRequest(this.bucketName, fileObject.fileId()[0]);
      req.setProcess(String.format(style, width,height));
      URL url = ossClient.generatePresignedUrl(req);
      return url.toURI().toURL().toString();
    }
  }

  @Override
  public FileUploadClient get(String bucketName) {
    return clientMap.get(bucketName);
  }
}
